/**
 ----------------------
 1.整张表的增删改查
 2.逻辑复用
 ----------------------
 */
import { useUploadFile } from '@/utils/file/file';
import { districtFormConfig } from './form';
import { districtTable } from './table';
import {
  deleteDistrict,
  fetchDistrictById,
  fetchDistrictList,
  exportDistrict,
  importDistrict,
} from '@/api/modules/ax/district/district';
import { response } from '@/utils/table/table';
import { setContextMenu } from '@/views/components/contextmenu/data';
import type { AxDistrict } from '@/api/modules/ax/district/types';
/**
 * @description: 根据条件获取列表数据
 */
export const districtList = async () => {
  try {
    districtTable.value.loading = true;
    const { data } = await fetchDistrictList(districtTable.value.query);
    districtTable.value.data = data.rows;
    districtTable.value.query.total = data.total;
    districtTable.value.loading = false;
  } catch (error) {
    districtTable.value.loading = false;
  }
};

/**
 * @description: 根据ID查询数据,并打开表单页面
 * @param {number} id
 */
export const districtEdit = async (id?: number|string) => {
  let targetId: number | string = id ? id : districtTable.value.keys[0];
  districtTable.value.loading = true;
  const { data } = await fetchDistrictById(targetId);
  if (data.data) {
    districtFormConfig.value.form = data.data;
    districtFormConfig.value.display = true;
  }
  districtTable.value.loading = false;
};

/**
 * @description:
 * 清空表单所有内容
 * 打开表单页面
 */
export const districtCreate = async () => {
  districtFormConfig.value.display = true;
  districtFormConfig.value.reset!();
};

export const districtDelete = async (id?: number) => {
  let ids = id ? [id] : districtTable.value.keys;
  await response(deleteDistrict, ids);
  await districtList();
  districtTable.value.keys = [];
};

// 导出EXCEL文件
export const districtExport = () => {
  return exportDistrict(districtTable.value.query);
};

/**
 * @description:搜索
 * 需要将页码设为第一页，避免翻页后搜不到内容
 */
export const districtSearch = () => {
  districtTable.value.query.pageNum = 1;
  districtList();
};

/**
 * @description: 使用excel导入文件
 */
export const districtImport = async () => {
  const files = await useUploadFile({
    accept: '.xls, .xlsx',
  });
  importDistrict(files[0]);
};

/**
 * @description:
 *  显示右键菜单
 *  在表格和卡片中复用
 * @param {AxDistrict} item
 */
export const displayDistrictMenu = (item: AxDistrict) => {
  districtFormConfig.value.form = item;
  districtTable.value.keys = [item.districtId];
  setContextMenu({
    items: districtTable.value.contextmenu,
  });
};
